﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace NetworkSwitch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Thread threa;

        public void Getdevice()
        {
            StringBuilder sbDevHst = new StringBuilder();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity where Name='"+ AppConfig.NetworkAdapter+"'");
            bool exists = false;
            foreach (ManagementObject mgt in searcher.Get())
            {
                exists = true;
                break;
            }

            //当前网络是内网，且存在外网网卡，则切换双网络
            if ((AppConfig.NetworkType == 1|| AppConfig.NetworkType == 3) && exists)
            {
                if (GetInternetNetWork())
                {
                    AppConfig.NetworkType = 2;
                    ChangeColor();
                }
            }
            else if ((AppConfig.NetworkType == 2 || AppConfig.NetworkType == 3) && !exists) //当前网络是外网，且不存在外网网卡，则切换内网
            {
                if (GetLocalNetWork())
                {
                    AppConfig.NetworkType = 1;
                    ChangeColor();
                }
            }

            Thread.Sleep(2000);
            Getdevice();
        }

        private bool GetLocalNetWork()
        {
            try
            {
                var cmds = new List<string>();
                cmds.Add("route delete 0.0.0.0");
                cmds.Add("route delete 192.168.0.0");
                cmds.Add("route add -p 0.0.0.0 mask 0.0.0.0 " + AppConfig.LocalNetWork);
                ExecCmd(cmds);
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

        private bool GetInternetNetWork()
        {
            try
            {
                var cmds = new List<string>();
                cmds.Add("route delete 0.0.0.0");
                cmds.Add("route add -p 192.168.0.0 mask 255.255.0.0 " + AppConfig.LocalNetWork);
                cmds.Add("route add -p 0.0.0.0 mask 0.0.0.0 " + AppConfig.Internet);
                ExecCmd(cmds);
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

        private bool GetOnlyInternetNetWork()
        {
            try
            {
                var cmds = new List<string>();
                cmds.Add("route delete 0.0.0.0");
                cmds.Add("route delete 192.168.0.0");
                cmds.Add("route add -p 0.0.0.0 mask 0.0.0.0 " + AppConfig.Internet);
                ExecCmd(cmds);
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

        private bool ExecCmd(List<string> cmds)
        {
            Process p = new Process();
            p.StartInfo.FileName = "PowerShell.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.Verb = "runas";
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            foreach (string cmd in cmds)
            {
                p.StandardInput.WriteLine(cmd);
            }           
            p.StandardInput.AutoFlush = true;            
            p.Close();

            return true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {           
            //取消关闭窗口
            e.Cancel = true;
            //最小化主窗口
            this.WindowState = FormWindowState.Minimized;
            //任务栏取消图标
            this.ShowInTaskbar = false;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                //还原窗体
                this.WindowState = FormWindowState.Normal;
                //任务显示
                this.ShowInTaskbar = true;
            }
            //激活窗体
            this.Activate();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (threa != null && threa.IsAlive)
            {
                threa.Abort();
            }
            this.Dispose();
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ChangeColor();
        }

        private bool ChangeColor()
        {
            switch (AppConfig.NetworkType)
            {
                case 1:
                    btnOnlyInternet.ForeColor = Color.Black;
                    btnInternet.ForeColor = Color.Black;
                    btnLocal.ForeColor = Color.Red;
                    break;
                case 2:
                    btnOnlyInternet.ForeColor = Color.Black;
                    btnLocal.ForeColor = Color.Black;
                    btnInternet.ForeColor = Color.Red;
                    break;
                case 3:
                    btnOnlyInternet.ForeColor = Color.Red;
                    btnLocal.ForeColor = Color.Black;
                    btnInternet.ForeColor = Color.Black;
                    break;
            }

            btnListen.Enabled = !string.IsNullOrEmpty(AppConfig.NetworkAdapter);
            btnLocal.Enabled = !string.IsNullOrEmpty(AppConfig.LocalNetWork);
            btnInternet.Enabled = !string.IsNullOrEmpty(AppConfig.Internet);

            return true;
        }

        private void btnInternet_Click(object sender, EventArgs e)
        {
            if (GetInternetNetWork())
            {
                AppConfig.NetworkType = 2;
                ChangeColor();
            }
        }

        private void btnLocal_Click(object sender, EventArgs e)
        {
            if (GetLocalNetWork())
            {
                AppConfig.NetworkType = 1;
                ChangeColor();
            }
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            if (threa != null && threa.IsAlive)
            {
                threa.Abort();
                btnListen.Text = "启动监听";
            }
            else
            {
                threa = new Thread(new ThreadStart(Getdevice));
                threa.Start();
                btnListen.Text = "停止监听";
            }
        }

        private void btnOnlyInternet_Click(object sender, EventArgs e)
        {
            if (GetOnlyInternetNetWork())
            {
                AppConfig.NetworkType = 3;
                ChangeColor();
            }
        }
    }
}
